package com.zzyl.nursing.service.impl;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.BindingMemberElderDto;
import com.zzyl.nursing.dto.MemberDayDeviceDataDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.IBedService;
import com.zzyl.nursing.service.IElderService;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.stream.Collectors;

/**
 * 老人家属Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-26
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper,FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private IElderService elderService;
    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

    /**
     * 按照周获取当前登录用户的家人健康数据
     *
     * @param dto
     * @return
     */

    @Override
    public List<MemberDayDataVo> queryDeviceDataListByWeek(MemberDayDeviceDataDto dto) {
        List<MemberDayDataVo> list = new ArrayList<>();
        long startTime = dto.getStartTime();
        long endTime = startTime + 3600 * 1000 *  23;
        while(endTime<dto.getEndTime()){
            //构建按天查询的参数
            MemberDayDeviceDataDto dayTime = BeanUtil.toBean(dto, MemberDayDeviceDataDto.class);
            dayTime.setStartTime(startTime);
            dayTime.setEndTime(endTime);
            //调用按天查询的数据
            List<MemberDayDataVo> memberDayDataVos = queryDeviceDataListByDay(dayTime);
            //拿出所有数据值取平均
            double sum = 0.0;
            double count =0.0;
            for (MemberDayDataVo memberDayDataVo : memberDayDataVos) {
                if (memberDayDataVo.getDataValue()!=0.0){
                    sum+=memberDayDataVo.getDataValue();
                    count++;
                }
            }
            double avg = sum/count;
            avg = Math.rint(avg);
            //构建每天的对象
            MemberDayDataVo data = new MemberDayDataVo();
            data.setDataValue(avg);
            //转换时间对象
            Instant instant = Instant.ofEpochMilli(startTime);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM.dd")
                    .withZone(ZoneId.systemDefault()); // 使用系统默认时区
            data.setDateTime(formatter.format(instant));

            //将对象添加到集合中
            list.add(data);

            //天数加一
            startTime = startTime  + 3600 * 1000 *  24;
            endTime = endTime + 3600 * 1000 *  24;
        }

        return list;
    }

    /**
     * 按照天获取当前登录用户的家人健康数据
     *
     * @param dto
     * @return
     */
    @Override
    public List<MemberDayDataVo> queryDeviceDataListByDay(MemberDayDeviceDataDto dto) {
        //按照开始和结束时间,查找该设备的心率数据
        //时间戳转换为日期
        LocalDateTime startTime = Instant.ofEpochMilli(dto.getStartTime())
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();
        LocalDateTime endTime = Instant.ofEpochMilli(dto.getEndTime())
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();
        startTime = startTime.truncatedTo(ChronoUnit.HOURS);
        endTime = endTime.truncatedTo(ChronoUnit.HOURS);
        //把中间所有整数时间点添加到集合中
        List<LocalDateTime> hourlyPoints = new ArrayList<>();

        // 添加范围内的所有整点
        LocalDateTime current = startTime;
        while (!current.isAfter(endTime)) {
            hourlyPoints.add(current);
            current = current.plusHours(1);
        }

        //查找每个时间点的数据
        List<MemberDayDataVo> memberDayDataVos = hourlyPoints.stream().map(time -> {
            //创建对象储存数据
            MemberDayDataVo memberDayDataVo = new MemberDayDataVo();
            //添加时间
            memberDayDataVo.setDateTime(time.toString());
            DeviceData deviceData = deviceDataMapper.selectOne(Wrappers.<DeviceData>lambdaQuery()
                    .eq(DeviceData::getIotId, dto.getIotId())
                    .eq(DeviceData::getFunctionId, dto.getFunctionId())
                    .ge(DeviceData::getAlarmTime, time)
                    .orderByAsc(DeviceData::getAlarmTime)
                    .last("LIMIT 1"));
            if (ObjectUtil.isEmpty(deviceData)){
                //值不存在,设置为0
                memberDayDataVo.setDataValue(0.0);
            }else {
                String dataValue = deviceData.getDataValue();
                memberDayDataVo.setDataValue(Math.rint(Double.valueOf(dataValue)));
            }
            return memberDayDataVo;
        }).collect(Collectors.toList());


        return memberDayDataVos;
    }

    /**
     * 获取当前登录用户的家人健康数据
     *
     * @param iotId
     * @return
     */
    @Override
    public List<MemberElderHealthVo> getHealthData(String iotId) {
        //从redis中获取数据
        String jsonStr = (String) redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, iotId);
        List<DeviceData> list = JSONUtil.toList(jsonStr, DeviceData.class);
        List<MemberElderHealthVo> healthDats = list.stream().map(deviceData -> {
            MemberElderHealthVo healthData = new MemberElderHealthVo();
            healthData.setFunctionId(deviceData.getFunctionId());
            healthData.setValue(Double.valueOf(deviceData.getDataValue()));
            //日期转换为字符串
            healthData.setEventTime(deviceData.getAlarmTime().toString());
            return healthData;
        }).collect(Collectors.toList());

        return healthDats;
    }

    /**
     * 分页查询当前登录用户的家人信息
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<MemberElderInfoVo> listByPage(Integer pageNum, Integer pageSize) {
        // 获取当前登录人
        Long userId = UserThreadLocal.getUserId();
        //根据登录人id查询所有绑定的老人
        List<FamilyMemberElder> familyMemberElders = familyMemberElderMapper.selectList(Wrappers.<FamilyMemberElder>lambdaQuery().eq(FamilyMemberElder::getFamilyMemberId, userId));
        if (CollUtil.isEmpty(familyMemberElders)){
            throw new BaseException("没有绑定老人");
        }
        //调用Mapper层查询所有数据
        List<MemberElderInfoVo> memberElderInfoVos = familyMemberElderMapper.listByPage(userId);

        return memberElderInfoVos;
    }

    /**
     * 获取当前登录用户的家人信息
     *
     * @return
     */
    @Override
    public List<SelectMemberElderVo> getMyElders() {
        //获取当前登录人
        Long userId = UserThreadLocal.getUserId();
        return familyMemberElderMapper.selectAllBinding(userId);
    }

    /**
     * 小程序用户绑定老人
     */
    @Override
    public Integer bingElder(BindingMemberElderDto dto) {
        //获取当前登录用户id
        Long userId = UserThreadLocal.getUserId();
        //根据身份证号获得老人id
        String idCard = dto.getIdCard();
        Elder elder = elderService.getOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, idCard));
        //判断是否为空
        if (ObjectUtil.isEmpty(elder)){
            throw new BaseException("您输入的身份证号有误");
        }
        Long elderId = elder.getId();
        //判断当前用户是否已绑定该老人
        FamilyMemberElder familyMemberElderExit = familyMemberElderMapper.selectOne(Wrappers.<FamilyMemberElder>lambdaQuery().eq(FamilyMemberElder::getFamilyMemberId, userId).eq(FamilyMemberElder::getElderId, elderId));
        if (ObjectUtil.isNotEmpty(familyMemberElderExit)){
            throw new BaseException("您已绑定该老人");
        }
        //创建实体类
        FamilyMemberElder familyMemberElder = new FamilyMemberElder();
        familyMemberElder.setFamilyMemberId(userId);
        familyMemberElder.setElderId(elderId);
        familyMemberElder.setRemark(dto.getRemark());

        return familyMemberElderMapper.insert(familyMemberElder)>0?1:0;

    }

    /**
     * 查询老人家属
     * 
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     * 
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return save(familyMember)?1:0;
    }

    /**
     * 修改老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return updateById(familyMember)?1:0;
    }

    /**
     * 批量删除老人家属
     * 
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除老人家属信息
     * 
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return removeById(id)?1:0;
    }

    @Autowired
    private WechatService wechatService;

    @Autowired
    private TokenService tokenService;

    /**
     * 小程序端登录
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {

        //获取openid  微信接口获取
        String openid = wechatService.getOpenid(dto.getCode());

        //根据openid查询用户信息
        FamilyMember familyMember = getOne(Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openid));

        //如果用户为空，构建用户，赋值一个openid
        if(ObjectUtil.isEmpty(familyMember)){
            familyMember = FamilyMember
                    .builder()
                    .openId(openid)
                    .build();
        }

        //获取用户的手机号  微信接口获取
        String phone = wechatService.getPhone(dto.getPhoneCode());

        //保存或更新用户
        insertOrUpdateFamilyMember(familyMember,phone);

        //生成token返回
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", familyMember.getId());
        claims.put("userName", familyMember.getName());

        String token = tokenService.createToken(claims);
        LoginVo loginVo = new LoginVo();
        loginVo.setNickName(familyMember.getName());
        loginVo.setToken(token);

        return loginVo;
    }

    /**
     * 保存或更新用户
     * @param familyMember
     * @param phone
     */
    private void insertOrUpdateFamilyMember(FamilyMember familyMember, String phone) {

        //判断手机号与数据库的手机号是否一致
        if(ObjectUtil.notEqual(familyMember.getPhone(),phone)){
            familyMember.setPhone(phone);
        }
        //判断是否存在id，如果存在id，则更新，不存在则保存
        if(ObjectUtil.isNotEmpty(familyMember.getId())){
            updateById(familyMember);
            return;
        }
        //获取用户的昵称
        int index = (int)(Math.random() * DEFAULT_NICKNAME_PREFIX.size());
        String nickName = DEFAULT_NICKNAME_PREFIX.get(index) + StringUtils.substring(phone,7,11);
        familyMember.setName(nickName);
        //保存
        save(familyMember);

    }
}
